<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_pairing_matching($in_year, $in_month, $in_day){
	global $vars;
	$db=$vars["db"];
	$pairing_percent_per_pair = $vars['pairing_percent_per_pair'];
	$rank_index_a_bv = $vars['rank_index_a_bv'];
	$max_pair_per_day = $vars['max_pair_per_day'];
	$matching_bonus = $vars['matching_bonus'];
	$maintenance_percent = $vars['maintenance_percent'];
	$max_maintain = $vars['max_maintain'];		$jp_max_maintain = $vars['jp_max_maintain'];
	
	$start_time=mktime(0, 0, 0, $in_month, $in_day, $in_year);
	$calc_date['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $in_month, $in_day, $in_year));
	$calc_date['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $in_month, $in_day, $in_year));
	$calc_date2['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $in_month, 1, $in_year));
	$calc_date2['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $in_month+1, 0, $in_year));
	$last_day=date('Y-m-d', mktime(0, 0, 0, $in_month, $in_day-1, $in_year));
	$maintain_time=mktime(0, 0, 0, $in_month, 1, $in_year);
	$maintain_year = date("Y", $maintain_time);
	$maintain_month = date("n", $maintain_time);
	
	$matching_max_level = count($matching_bonus);
	$min_maintain = $vars['min_maintain'];
	
	$sales_his_safe = false;
	if(!mysql_query("truncate $db->purchase_calc")){
		$sales_his_safe = true;
	}else{
		$ins_total = 0;
		$t = @mysql_num_rows($r=mysql_query("select id, uid, total_bv from $db->purchase where status='confirmed' and member_sale='y' and first_sale='y' and no_bv!='y' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"));
		for($i=0;$i<$t;$i++){
			$his = mysql_fetch_assoc($r);
			$ins .= "('$his[id]', '$his[uid]', '$his[total_bv]'),";
			$ins_total++;
			if($ins_total > 200){
				$ins = rtrim($ins, ',');
				$ins_sql = "insert into $db->purchase_calc (id, uid, total_bv) values $ins";
				if(!mysql_query($ins_sql)){
					$i = $t;
					$sales_his_safe = true;
				}
				$ins = '';
				$ins_total = 0;
			}
		}
		if($ins){
			$ins = rtrim($ins, ',');
			$ins_sql = "insert into $db->purchase_calc (id, uid, total_bv) values $ins";
			if(!mysql_query($ins_sql)){
				$sales_his_safe = true;
			}
		}
		unset($his, $ins, $ins_sql, $ins_total);
	}
	$carryforward_safe = false;
	if(!mysql_query("truncate $db->member_cf_calc")){
		$carryforward_safe = true;
	}else{
		$ins_total = 0;
		$t = @mysql_num_rows($r=mysql_query("select uid, amount from $db->member_cf where cdate='$last_day'"));
		for($i=0;$i<$t;$i++){
			$his = mysql_fetch_assoc($r);
			$ins .= "('$his[uid]', '$his[amount]'),";
			$ins_total++;
			if($ins_total > 200){
				$ins = rtrim($ins, ',');
				$ins_sql = "insert into $db->member_cf_calc (uid, amount) values $ins";
				if(!mysql_query($ins_sql)){
					$i = $t;
					$carryforward_safe = true;
				}
				$ins = '';
				$ins_total = 0;
			}
		}
		if($ins){
			$ins = rtrim($ins, ',');
			$ins_sql = "insert into $db->member_cf_calc (uid, amount) values $ins";
			if(!mysql_query($ins_sql)){
				$carryforward_safe = true;
			}
		}
		unset($his, $ins, $ins_sql, $ins_total);
	}
	$t=@mysql_num_rows($r=mysql_query("select id, rank_a from $db->users where activated='y' order by id desc"));
	for($i=0;$i<$t;$i++){
		$member = mysql_fetch_assoc($r);
		$uid = $member['id'];
		if ($member['rank_a'] > 0){
			$t2 = @mysql_num_rows($r2=mysql_query("select id, matrix_position from $db->users where matrix_upline='$uid'"));
			for($j=0;$j<$t2;$j++){
				$downline = mysql_fetch_assoc($r2);
				$did = $downline['id'];
				$position = $downline['matrix_position'];
				$all_did = $did;
				$uplines[0] = $did;
				$this_volume = 0;
				do{
					$t3 = @mysql_num_rows($r3=mysql_query("select id from $db->users where matrix_upline in (".implode(',', $uplines).")"));
					unset ($uplines);
					for($k=0;$k<$t3;$k++){
						$ddownlines = mysql_fetch_assoc($r3);
						$ddid = $ddownlines['id'];
						if($member_legss[$ddid]){
							foreach($member_legss[$ddid] as $details){
								$this_volume += $details['avolume'];
							}
						}else{
							$uplines[] = $ddid;
						}
						$all_did .= ','.$ddid;
					}
				}while ($uplines);
				
				if($sales_his_safe){
					$sql = "select sum(total_bv) from $db->purchase where first_sale='y' and no_bv!='y' and uid in ($all_did) and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'";
				}else{
					$sql = "select sum(total_bv) from $db->purchase_calc where uid in ($all_did)";
				}
				$volume = @mysql_result(mysql_query($sql), 0) or 0;
				if($carryforward_safe){
					$sql = "select amount from $db->member_cf where uid='$did' and cdate='$last_day'";
				}else{
					$sql = "select amount from $db->member_cf_calc where uid='$did'";
				}
				$carryforward = @mysql_result(mysql_query($sql), 0) or 0;
				
				$total_bv = $volume + $this_volume + $carryforward;
				$total_abv = $volume + $this_volume;
				$downlines_id[$j] = $did;
				$downlines_bv[$j] = $total_bv;
				$downlines_dd[$did]['position'] = $position;
				$downlines_dd[$did]['volume'] = $total_bv;
				$downlines_dd[$did]['avolume'] = $total_abv;
			}
			if($downlines_id && $downlines_bv){
				array_multisort($downlines_bv, SORT_DESC, $downlines_id, SORT_ASC);
				for($j=0,$t2=count($downlines_id);$j<$t2;$j++){
					$legs[$j]["id"]=$downlines_id[$j];
					$legs[$j]['position'] = $downlines_dd[$downlines_id[$j]]['position'];
					$legs[$j]['volume']=$downlines_bv[$j];
					$legs[$j]['left_volume'] = $downlines_bv[$j];
					$legs[$j]['avolume'] = $downlines_dd[$downlines_id[$j]]['avolume'];
				}
			}
			$member_legs = $legs;
			$member_legss[$uid] = $legs;
			unset ($legs, $downlines_id, $downlines_bv, $uplines, $all_did);
			$pairing_amount_per_pair = $rank_index_a_bv[$member['rank_a']];
			$max_pairing_amount = $pairing_amount_per_pair * $max_pair_per_day;
			$prev_position = 0;
			$cur_position = 1;
			unset ($max_pair_reached);
			$pi = 0;
			do{
				$continue_pair = false;
				if (isset($member_legs[$prev_position]) && isset($member_legs[$cur_position])){
					if ($member_legs[$prev_position]['left_volume'] > 0 && $member_legs[$cur_position]['volume'] > 0){
						$paired_amount = ($a = $member_legs[$prev_position]['left_volume']) > ($b = $member_legs[$cur_position]['volume'])? $b : $a;
						if ($paired_amount >= $max_pairing_amount){
							$paired_amount = $max_pairing_amount;
							$max_pair_reached[$cur_position] = true;
						}
						$paired_comm[$uid][$pi]['paired_amount'] = $paired_amount;
						$paired_comm[$uid][$pi]['leg1'] = $member_legs[$prev_position]['position'];
						$paired_comm[$uid][$pi]['leg1_id'] = $member_legs[$prev_position]['id'];
						$paired_comm[$uid][$pi]['leg1_amount'] = $member_legs[$prev_position]['left_volume'];
						$paired_comm[$uid][$pi]['leg2'] = $member_legs[$cur_position]['position'];
						$paired_comm[$uid][$pi]['leg2_id'] = $member_legs[$cur_position]['id'];
						$paired_comm[$uid][$pi]['leg2_amount'] = $member_legs[$cur_position]['left_volume'];
						$pi++;
						$member_legs[$prev_position]['left_volume'] -= $paired_amount;
						$member_legs[$cur_position]['left_volume'] -= $paired_amount;
						if ($max_pair_reached[$cur_position]){
							if ($member_legs[$prev_position]['left_volume'] < $member_legs[$cur_position]['left_volume']){
								$member_legs[$prev_position]['left_volume'] = 0;
							}else{
								$member_legs[$cur_position]['left_volume'] = 0;
							}
						}
						if ($member_legs[$prev_position]['left_volume'] < $member_legs[$cur_position]['left_volume']){
							$prev_position = $cur_position;
						}
						$cur_position += 1;
						$continue_pair = true;
					}
				}
			}while ($continue_pair);
			
			for($j=0,$t2=count($member_legs);$j<$t2;$j++){
				if ($member_legs[$j]['left_volume'] > 0){
					$sql="insert into $db->member_cf (uid, leg, amount, cdate) values ('{$member_legs[$j]['id']}', '{$member_legs[$j]['position']}', '{$member_legs[$j]['left_volume']}', '".date('Y-m-d', $start_time)."')";
					$insert_comm_detail="UID: $uid Carryforward Amount: {$member_legs[$j]['left_volume']} Leg: {$member_legs[$j]['position']} (DID: {$member_legs[$j]['id']})<br />\n";
					if(!mysql_query($sql)){
						$insert_cf_error.=$insert_comm_detail."SQL: $sql<br />\n";
					}
				}
			}
			
			if (count($paired_comm[$uid])){
				for($j=0,$t2=count($paired_comm[$uid]);$j<$t2;$j++){
					unset ($pairing_id);
					$pairing_comm_amount = round($paired_comm[$uid][$j]['paired_amount'] * $pairing_percent_per_pair / 100, 2);
					$sql="insert into $db->member_comm (uid, type, volume_type, amount, leg1, leg1_id, leg1_amount, leg2, leg2_id, leg2_amount, year, month, day, status, cdate) values ('$uid', 'p', '$pairing_amount_per_pair', '$pairing_comm_amount', '{$paired_comm[$uid][$j]['leg1']}', '{$paired_comm[$uid][$j]['leg1_id']}', '{$paired_comm[$uid][$j]['leg1_amount']}', '{$paired_comm[$uid][$j]['leg2']}', '{$paired_comm[$uid][$j]['leg2_id']}', '{$paired_comm[$uid][$j]['leg2_amount']}', '$in_year', '$in_month', '$in_day', 'confirmed', '".ndate('Y-m-d H:i:s')."')";
					$insert_comm_detail="UID: $uid Volume Type: $pairing_amount_per_pair Amount: $pairing_comm_amount Leg 1: {$paired_comm[$uid][$j]['leg1_id']}, Leg 2: {$paired_comm[$uid][$j]['leg2_id']} No. of Pair: $paired_unit<br />\n";
					if(!mysql_query($sql)){
						$insert_pair_error.=$insert_comm_detail."SQL: $sql<br />\n";
					}else{
						$insert_pair_success.=$insert_comm_detail;
						$pairing_id = mysql_insert_id();
					}
					$member_comm[$uid] += $pairing_comm_amount;
					$downline_id = $uid;
					$level = $actual_level = 1;
					do{
						$this_user = get_user_detail_by_id($downline_id);
						$upline = get_user_detail_by_id($this_user['ref']);
						unset ($downline_id);
						if ($upline){
							$upline_id = $upline['id'];
							if (!isset($upline_info[$upline_id])){
								$upline_info[$upline_id]['sponsor'] = @mysql_result(mysql_query("select count(*) from $db->users where ref='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
								$upline_info[$upline_id]['downline'] = @mysql_result(mysql_query("select count(*) from $db->users where matrix_upline='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
							}
							if ($upline_info[$upline_id]['sponsor'] >= $matching_bonus[$level]['sponsor'] && $upline_info[$upline_id]['downline'] >= $matching_bonus[$level]['downline'] && $upline['activated'] == 'y'){
								$matching_comm_percent = $matching_bonus[$level]['percent'];
								$matching_comm_amount = round($pairing_comm_amount * $matching_comm_percent / 100, 2);
								if ($pairing_id){
									$sql="insert into $db->member_comm (uid, from_uid, type, pid, amount, level, level2, percent, year, month, day, status, cdate) values ('$upline_id', '$uid', 'm', '$pairing_id', '$matching_comm_amount', '$level', '$actual_level', '$matching_comm_percent', '$in_year', '$in_month', '$in_day', 'confirmed', '".ndate('Y-m-d H:i:s')."')";
									$insert_comm_detail="UID: $upline_id Pairing ID: $pairing_id Amount: $matching_comm_amount Level: $level Percent: $matching_comm_percent%<br />\n";
									if(!mysql_query($sql)){
										$insert_matching_error.=$insert_comm_detail."SQL: $sql<br />\n";
									}else{
										$insert_matching_success.=$insert_comm_detail;
									}
								}else{
									$insert_matching_error.="UID: $uid Pairing ID: Error! Amount: $matching_comm_amount Level: $level Percent: $matching_comm_percent%<br />\n";
								}
								$level++;
							}
							$downline_id = $upline_id;
						}
						$actual_level++;
					}while ($downline_id && $level <= $matching_max_level);
				}
			}
		}
	}
	
	if ($member_comm && !($in_year==2010 && $in_month==3 && $in_day>=6 && $in_day<=14)){
		foreach ($member_comm as $uid => $amount){
			$total_maintain_amount = $maintain_amount = round($amount * $maintenance_percent / 100, 2);
			$next_month_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$uid' and year='$maintain_year' and month='$maintain_month'"), 0) or 0;			$user_country = @mysql_result(mysql_query("select country from $db->users where id='$uid'"), 0) or 0;						if($user_country=='JP'){				if($next_month_maintain < $jp_max_maintain){					$maintain_amount = round($amount * $maintenance_percent / 100, 2);						if($maintain_amount + $next_month_maintain > $jp_max_maintain){							$maintain_amount = $jp_max_maintain - $next_month_maintain;						}						$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)						values ('$uid', 'p', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";						if(!mysql_query($sql)){							$insert_main_err.="UID: $uid, comm code: p, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";						}					}else{						$maintain_amount = 0;					}			}else{				if($next_month_maintain < $max_maintain){					$maintain_amount = round($amount * $maintenance_percent / 100, 2);						if($maintain_amount + $next_month_maintain > $max_maintain){							$maintain_amount = $max_maintain - $next_month_maintain;						}						$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)						values ('$uid', 'p', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";						if(!mysql_query($sql)){							$insert_main_err.="UID: $uid, comm code: p, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";						}					}else{						$maintain_amount = 0;					}			}			
			
			$actual_amount = $amount - $total_maintain_amount;
			if(!mysql_query($sql="update $db->users set ewallet=ewallet+$actual_amount where id='$uid' limit 1")){
				$update_ew_err.="UID: $uid, amount: $actual_amount\n";
			}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$amount', '".addslashes("Credited $vars[currency]".number_format($amount, 2)." from bulk pairing commission received.")."', '".ndate()."')")){
				$insert_ewrec_err.=$sql."\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal += $amount;
				@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
			
			if($maintain_amount > 0){
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$maintain_amount', '".addslashes("Debited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk pairing commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $maintain_amount;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				if(!mysql_query($sql="update $db->users set swallet=swallet+$maintain_amount where id='$uid' limit 1")){
					$update_sw_err.="UID: $uid, amount: $maintain_amount\n";
				}elseif(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$maintain_amount', '".addslashes("Credited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk pairing commission received.")."', '".ndate()."')")){
					$insert_swrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_swallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $maintain_amount;
					@mysql_query("update $db->member_swallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
			$mall_point = $total_maintain_amount - $maintain_amount;
			if($mall_point > 0){
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$mall_point', '".addslashes("Debited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk pairing commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $mall_point;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				if(!mysql_query($sql="update $db->users set mwallet=mwallet+$mall_point where id='$uid' limit 1")){
					$update_mw_err.="UID: $uid, amount: $mall_point\n";
				}elseif(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$mall_point', '".addslashes("Credited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk pairing commission received.")."', '".ndate()."')")){
					$insert_mwrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $mall_point;
					@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
		}
	}
	
	if ($matching_comm){
		foreach ($matching_comm as $uid => $amount){
			$total_maintain_amount = $maintain_amount = round($amount * $maintenance_percent / 100, 2);
			$next_month_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$uid' and year='$maintain_year' and month='$maintain_month'"), 0) or 0;			$user_country = @mysql_result(mysql_query("select country from $db->users where id='$uid'"), 0) or 0;						if($user_country=='JP'){				if($next_month_maintain < $jp_max_maintain){					$maintain_amount = round($amount * $maintenance_percent / 100, 2);						if($maintain_amount + $next_month_maintain > $jp_max_maintain){							$maintain_amount = $jp_max_maintain - $next_month_maintain;						}						$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)						values ('$uid', 'm', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";						if(!mysql_query($sql)){							$insert_main_err.="UID: $uid, comm code: m, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";						}					}else{						$maintain_amount = 0;					}			}else{				if($next_month_maintain < $max_maintain){					$maintain_amount = round($amount * $maintenance_percent / 100, 2);						if($maintain_amount + $next_month_maintain > $max_maintain){							$maintain_amount = $max_maintain - $next_month_maintain;						}						$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)						values ('$uid', 'm', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";						if(!mysql_query($sql)){							$insert_main_err.="UID: $uid, comm code: m, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";						}					}else{						$maintain_amount = 0;					}			}
			
			
			$actual_amount = $amount - $total_maintain_amount;
			if(!mysql_query($sql="update $db->users set ewallet=ewallet+$actual_amount where id='$uid' limit 1")){
				$update_ew_err.="UID: $uid, amount: $actual_amount\n";
			}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$amount', '".addslashes("Credited $vars[currency]".number_format($amount, 2)." from bulk matching commission received.")."', '".ndate()."')")){
				$insert_ewrec_err.=$sql."\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal += $amount;
				@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
			
			if($maintain_amount > 0){
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$maintain_amount', '".addslashes("Debited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $maintain_amount;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				if(!mysql_query($sql="update $db->users set swallet=swallet+$maintain_amount where id='$uid' limit 1")){
					$update_sw_err.="UID: $uid, amount: $maintain_amount\n";
				}elseif(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$maintain_amount', '".addslashes("Credited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_swrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_swallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $maintain_amount;
					@mysql_query("update $db->member_swallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
			$mall_point = $total_maintain_amount - $maintain_amount;
			if($mall_point > 0){
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$mall_point', '".addslashes("Debited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $mall_point;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				if(!mysql_query($sql="update $db->users set mwallet=mwallet+$mall_point where id='$uid' limit 1")){
					$update_mw_err.="UID: $uid, amount: $mall_point\n";
				}elseif(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$mall_point', '".addslashes("Credited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_mwrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $mall_point;
					@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
		}
	}
	
	if($insert_cf_error || $insert_pair_error || $insert_matching_error || $insert_main_err){
		$status = false;
	}else{
		$status = true;
	}
	
	$errmsg = ($insert_cf_error? "\nFailed Recording Carry Forward:\n\n$insert_cf_error" : "").
	($insert_pair_error? "Failed Pairing Commission Calculation:<br />\n<br />\n$insert_pair_error" : "").
	($insert_matching_error? "Failed Matching Commission Calculation:<br />\n<br />\n$insert_matching_error" : "").
	($insert_main_error? "Failed Maintenance Calculation:<br />\n<br />\n$insert_main_error" : "").
	($update_ew_err? "\nError crediting $vars[ewallet_title]:\n\n$update_ew_err" : "").
	($insert_ewrec_err? "\nError crediting $vars[ewallet_title] transactin record:\n\n$insert_ewrec_err" : "").
	($update_sw_err? "\nError crediting $vars[swallet_title]:\n\n$update_sw_err" : "").
	($insert_swrec_err? "\nError crediting $vars[swallet_title] transactin record:\n\n$insert_swrec_err" : "").
	($update_mw_err? "\nError crediting $vars[mwallet_title]:\n\n$update_mw_err" : "").
	($insert_mwrec_err? "\nError crediting $vars[mwallet_title] transactin record:\n\n$insert_mwrec_err" : "");
	
	return array('status'=>$status, 'errmsg'=>$errmsg);
}
?>